package org.kjtc.security;

import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.kjtc.entity.UserAccessInfo;
import org.kjtc.service.UserInfoService;
import org.kjtc.util.AddressUtils;
import org.kjtc.util.Const;
import org.kjtc.util.Loggers;
import org.kjtc.util.Tools;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;

public class AuthenticationSuccessHandler extends
		SavedRequestAwareAuthenticationSuccessHandler {

	protected final Loggers logger = Loggers.getLogger(this.getClass());
	private final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST";

	private String specialRoleUrl = "/";

	@Resource(name = "userInfoService")
	private UserInfoService userInfoService;

	@SuppressWarnings("unused")
	private RequestCache requestCache = new HttpSessionRequestCache();

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {

		HttpSession session = request.getSession();
		session.setAttribute(Const.SESSION_USER, authentication.getPrincipal());
		session.removeAttribute(SAVED_REQUEST);
		UserAccessInfo userAccessInfo = new UserAccessInfo();
		userAccessInfo.setUserID(request.getParameter("username"));
		userAccessInfo.setOnloadEquipment(Tools.getOnloadEquipment(request));
		Date now = new Date();
		userAccessInfo.setOnloadTime(now);
		userAccessInfo.setOnLineTime(now);
		now = null;
		userAccessInfo.setCreateUser(request.getParameter("username"));
		userAccessInfo.setUpdateUser(request.getParameter("username"));
		String ip = null;
		try {
			ip = Tools.getIPAddress(request);
		} catch (Exception e) {
			logger.error("用户登录记录：登录获取IP异常：" + e.getMessage());
			e.printStackTrace();
		}
		userAccessInfo.setOnloadIP(ip);
		userAccessInfo.setOnloadPort(String.valueOf(request.getRemotePort()));
		String json_result = null;
	    try {
	    	json_result = AddressUtils.getIpInfo("ip=" + ip);
	    	if (!"0".equals(json_result)) {
	    		JSONObject json = JSONObject.fromObject(json_result);
		    	if (json.has("data")) {
		    		JSONObject dataJson = JSONObject.fromObject(json.get("data"));
		    		if (dataJson.has("country") && dataJson.get("country").toString().indexOf("内网") == -1) {
		    			userAccessInfo.setLocation(dataJson.get("country").toString());
		    			if (dataJson.has("area") && dataJson.get("area") != null) {
			    			userAccessInfo.setLocation(userAccessInfo.getLocation() + "/" + dataJson.get("area").toString());
			    		}
			    		if (dataJson.has("region")) {
			    			userAccessInfo.setLocation(userAccessInfo.getLocation() + "/" + dataJson.get("region").toString());
			    			if (dataJson.has("city")) {
		    					if(!dataJson.get("region").toString().equals(dataJson.get("city").toString())) {
		    						userAccessInfo.setLocation(userAccessInfo.getLocation() + "/" + dataJson.get("city").toString());
		    					}
		    					if (dataJson.has("county")) {
		    						userAccessInfo.setLocation(userAccessInfo.getLocation() + "/" + dataJson.get("county").toString());
		    						if (dataJson.has("isp") && dataJson.get("isp") != null) {
		    			    			userAccessInfo.setLocation(userAccessInfo.getLocation() + "|" + dataJson.get("isp").toString());
		    			    		}
		    					}
				    		}
			    		}
		    		} else {
		    			userAccessInfo.setLocation("内网IP");
		    		}
		    	}
	    	}
	    } catch (Exception e) {
	    	logger.error("用户登录记录：获取位置区域异常：" + e.getMessage());
	        e.printStackTrace();
	    }
		ip = null;
		try {
			logger.info("用户登录记录：用户登录信息-" +
					"用户ID：" + userAccessInfo.getUserID() +
					"，登录时间：" + Tools.date2Str(userAccessInfo.getOnloadTime()) +
					"，登录设备：" + userAccessInfo.getOnloadEquipment() +
					"，登录IP：" + userAccessInfo.getOnloadIP() +
					"，登录端口：" + userAccessInfo.getOnloadPort() +
					"，登录位置：" + userAccessInfo.getLocation()
					);
			userInfoService.saveUserAccessInfo(userAccessInfo);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("用户登录记录：用户登录信息保存异常：" + e.getMessage());
		}
		userAccessInfo = null;
		if (authentication.getAuthorities() != null) {
			 if (authentication.getAuthorities().iterator().hasNext() && authentication.getAuthorities().iterator().next().getAuthority().indexOf("SHRO") >= 0) {
				 getRedirectStrategy().sendRedirect(request, response, specialRoleUrl);
			 }
		}
		super.onAuthenticationSuccess(request, response, authentication);
	}

	protected final String getSpecialRoleUrl() {
		return specialRoleUrl;
	}

	public void setSpecialRoleUrl(String specialRoleUrl) {
		Assert.isTrue(UrlUtils.isValidRedirectUrl(specialRoleUrl),
				"specialRoleUrl must start with '/' or with 'http(s)'");
		this.specialRoleUrl = specialRoleUrl;
	}
}
